package com.ews.onlineexchange.controller;

import java.io.FileInputStream;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.ews.onlineexchange.model.ServiceSupplier;



@Named
public class ServiceSupplierExporter implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	static DateFormat df;
	static {
		df = new SimpleDateFormat("yyyy-MM-dd");
	}
	
	private static final String[] FIELD_NAMES= {		
			"rowIndex","cnname",	"firstContactor","firstContactorPhoneNumber",""
		};
	@Inject
	EntityManager entityManager;
	private final static String GET_SERVICESUPPLIER_LIST = " "
			+ " 	SELECT supplier		"
			+ "		FROM ServiceSupplier supplier	"
			+ "		WHERE delFlag = '0'  ";
//			+ "		AND rownum < 10 ";

	public XSSFWorkbook export() {
		XSSFWorkbook workbook = null;
		try {
			String template = ServiceSupplierExporter.class.getClassLoader().getResource("ServiceSupplierTemplate.xlsx").getPath();			
        	FileInputStream fis=new FileInputStream(template);
	        workbook=new XSSFWorkbook(fis);
	        XSSFSheet sheet = (XSSFSheet)workbook.getSheetAt(0);
	        
			List<ServiceSupplier> entityList = entityManager.createQuery(GET_SERVICESUPPLIER_LIST).getResultList();
			List<CellStyle> styleList = new ArrayList<CellStyle>();
			int index = 0;
			for (ServiceSupplier supplier : entityList) {
				
				Row dataRow = null ;
				supplier.setRowIndex(index + 1);
				if(index == 0)dataRow = sheet.getRow(2 + index);
				else dataRow = sheet.createRow(2 + index);
				for (int j = 0; j < FIELD_NAMES.length; j++) {
					Cell cell = null;
					if(index == 0) {
						cell = dataRow.getCell(j);
						CellStyle cellStyle = cell.getCellStyle();
						cell.setCellStyle(cellStyle);
						styleList.add(cellStyle);
					}else {
						cell = dataRow.createCell(j);
						cell.setCellStyle(styleList.get(j));
					}
					String fieldValue = "";
					String fieldName = FIELD_NAMES[j];
					if(StringUtils.isNotBlank(fieldName))fieldValue =BeanUtils.getProperty(supplier, fieldName);
					cell.setCellValue(fieldValue);
				}
				index++;
			}
			return workbook;
//			return WorkBookUtil.getSteamedContentByWorkBook(fileName,workbook);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} 
	}
	
}
